package threadDemo;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Ajie
 * @date 2023/8/7
 * @function
 */


public class AtomicCounter_Demo {
    private final AtomicInteger count = new AtomicInteger(0);

    // 原子地增加计数器的值
    public int increment() {
        return count.incrementAndGet();
    }

    // 原子地减少计数器的值
    public int decrement() {
        return count.decrementAndGet();
    }

    // 获取当前的计数值
    public int getCount() {
        return count.get();
    }

    public static void main(String[] args) {
        AtomicCounter_Demo counter = new AtomicCounter_Demo();

        // 创建一个线程来增加计数器的值
        Thread incrementThread = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.increment();
            }
        });

        // 创建一个线程来减少计数器的值
        Thread decrementThread = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                counter.decrement();
                System.out.println("AtomicCounter_Demo:main:decrement:"+i);
            }
        });

        incrementThread.start();
        decrementThread.start();

        try {
            incrementThread.join();
            decrementThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Final count value: " + counter.getCount());
    }
}
